package com.huayi.server.Controller;

import com.huayi.server.Utils.RandomValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by mac on 2017/8/29.
 */
@Controller
public class ImageGenController {

    @Autowired
    JedisPool jedisPool;

    @Autowired
    RandomValidateCode randomValidateCode;

    //显示登陆验证码
    @RequestMapping("/getSysManageLoginCode")
    @ResponseBody
    public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request){
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");//设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        randomValidateCode.getRandcode(request, response,"imagecode");// 输出图片方法
        return "";
    }

    @RequestMapping("/checkTcode")
    @ResponseBody
    public String checkTcode(HttpServletResponse response, HttpServletRequest request){
        String validateCode = request.getParameter("validateCode");
        String code = null;
        //1:获取cookie里面的验证码信息
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("imagecode".equals(cookie.getName())) {
                code = cookie.getValue();
                break;
            }
        }

        //1:获取session验证码的信息
        //String code1 = (String) request.getSession().getAttribute("");
        //2:判断验证码是否正确
        Jedis jedis = jedisPool.getResource();
        String code3 =  jedis.get(request.getRequestedSessionId()+"imagecode");

        if(!StringUtils.isEmpty(validateCode) && validateCode.equals(code3)){
            return "ok";
        }

        return "error";
        //这里我没有进行字母大小模糊的验证处理，感兴趣的你可以去试一下！
    }

}
